//
//  CZChatVC.m
//  CZWeiXin
//
//  Created by Alvechen on 16/4/12.
//  Copyright © 2016年 alvechen. All rights reserved.
//

/*
 Error Domain=XMPPOutgoingFileTransferErrorDomain Code=-1 "Timeout waiting for recipient `disco#info` response." UserInfo={NSLocalizedDescription=Timeout waiting for recipient `disco#info` response.}
 Error Domain=XMPPOutgoingFileTransferErrorDomain Code=-1 "Unable to send SI offer; the recipient doesn't have the required features." UserInfo={NSLocalizedDescription=Unable to send SI offer; the recipient doesn't have the required features.}

 */

#import "CZChatVC.h"
#import "CZChatImgView.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>


@interface CZChatVC ()<UITableViewDataSource,UITableViewDelegate,XMPPStreamDelegate,UITextFieldDelegate,XMPPIncomingFileTransferDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,XMPPOutgoingFileTransferDelegate,XMPPvCardAvatarDelegate,AVAudioRecorderDelegate,AVAudioPlayerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *messageTF;

/// 按住说话
@property (weak, nonatomic) IBOutlet UIButton *pressTalk;
/// 语音按钮
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;

///聊天记录查询结果控制器
@property (nonatomic,strong) NSFetchedResultsController  *fetchedResultsController;

/**
 *  录音器
 */
@property (nonatomic,strong) AVAudioRecorder *audioRecorder;
/**
 *  播放器
 */
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;

/**
 *  记录当前录音的name
 */
@property (nonatomic,copy) NSString *recordName;
/**
 *  发送中状态图标
 */
@property (weak, nonatomic) IBOutlet UIImageView *sendInTheImageV;



@end

@implementation CZChatVC

- (NSFetchedResultsController *)fetchedResultsController{
    
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    //实例化
    
    //存储器
    XMPPMessageArchivingCoreDataStorage *storage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
    
    // 获取当前用户的JID
    XMPPJID *myJID = [CZXMPPManager shareInstance].xmppStream.myJID;
    
    //查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    //条件(谓词) bareJidStr：选中的联系人   streamBareJidStr：当前用户
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bareJidStr == %@ && streamBareJidStr = %@",self.jid.bare,myJID.bare];
    
    //排序描述器
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    request.sortDescriptors = @[sortDesc];
    request.predicate = predicate;
    
    //创建查询结果控制器
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:storage.mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    //执行查询
    NSError *error = nil;
    [_fetchedResultsController performFetch:&error];
    
    for (XMPPMessageArchiving_Message_CoreDataObject *aMessage in _fetchedResultsController.fetchedObjects) {
        
        
        //打印聊天信息
        NSLog(@"%@-%@",aMessage.bareJidStr,aMessage.body);
    }
    
    return _fetchedResultsController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"播放录音" style:UIBarButtonItemStylePlain target:self action:@selector(playerAudio)];
    
    //标题
    self.title = self.jid.bare;

    //流代理
    [[CZXMPPManager shareInstance].xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //文件接收代理
    [[CZXMPPManager shareInstance].xmppIncomingFileTransfer addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //文件发送代理
    [[CZXMPPManager shareInstance].xmppOutgoingFileTransfer addDelegate:self delegateQueue:dispatch_get_main_queue()];
    //成为个人资料头像模块代理
    [[CZXMPPManager shareInstance].xmppvCardAvatarModule addDelegate:self delegateQueue:dispatch_get_main_queue()];
    

    //获取数据
    [self fetchData];
    
    /*
        为 pressTalk 添加手势
     */
    // 按下开始录音
    [self.pressTalk addTarget:self action:@selector(startRecord) forControlEvents:UIControlEventTouchDown];
    // 抬起手指，保存录音
    [self.pressTalk addTarget:self action:@selector(saveRecord) forControlEvents:UIControlEventTouchUpInside];
    // 当一次触摸从控件窗口内部拖动到外部时：往上滑，提示取消录音
    [self.pressTalk addTarget:self action:@selector(promptCancelRecord) forControlEvents:UIControlEventTouchDragExit];
    // 所有在控件之外触摸抬起事件:往上滑后，抬起手指触发操作，取消录音
    [self.pressTalk addTarget:self action:@selector(CancelRecord) forControlEvents:UIControlEventTouchUpOutside];
    // 当一次触摸从控件窗口之外拖动到内部时：往上滑后又往下滑回来，继续录音
    [self.pressTalk addTarget:self action:@selector(continueRecord) forControlEvents:UIControlEventTouchDragEnter];
    
    
}

#pragma mark - funcs

- (void)fetchData{
    
    //隔一段时间再去取,让数据库保存好了,才能取到最新数据
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //重新获取数据
        [self.fetchedResultsController performFetch:nil];
        //刷新表格
        [self.tableView reloadData];
        
        //滚动
        NSInteger rowCount = self.fetchedResultsController.fetchedObjects.count;
        
        if (rowCount) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rowCount - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    });
}

- (void)playerAudio {
    NSLog(@"播放录音");
    
    if (!self.audioPlayer.playing) {
        NSError *error;
        NSLog(@"----%@",self.audioRecorder.url);
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.audioRecorder.url error:&error];
        //        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:@"/Users/WONG/Desktop/audio/record.pcm"] error:&error];
        self.audioPlayer.delegate = self;
        if (error != nil) {
            NSLog(@"Wrong init player:%@", error);
        }else{
            [self.audioPlayer play];
        }
    }else {
        [self.audioPlayer pause];
    }
}


- (void)startRecord {
    NSLog(@"按下开始录音");
    // 使用真机进行录音时, 需要额外配置
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError = nil;
    // 使用session进行类别声明AVAudioSessionCategoryPlayAndRecord、AVAudioSessionCategoryRecord
    [session setCategory:AVAudioSessionCategoryPlayAndRecord  error:&sessionError];
    if (sessionError) {
        NSLog(@"session进行类别声明 error = %@",sessionError);
    }
    
    /**
     *
     AVFormatIDKey  音乐格式，这里采用PCM格式
     AVSampleRateKey 采样率
     AVNumberOfChannelsKey 音乐通道数
     AVLinearPCMBitDepthKey,采样位数 默认 16
     AVLinearPCMIsFloatKey,采样信号是整数还是浮点数
     AVLinearPCMIsBigEndianKey,大端还是小端 是内存的组织方式
     AVEncoderAudioQualityKey,音频编码质量
     
     */
    NSDictionary *recordSetting = @{
                                    AVFormatIDKey               : @(kAudioFormatLinearPCM),
                                    AVSampleRateKey             : @(8000.f),
                                    AVNumberOfChannelsKey       : @(1),
                                    AVLinearPCMBitDepthKey      : @(16),
                                    AVLinearPCMIsNonInterleaved : @NO,
                                    AVLinearPCMIsFloatKey       : @NO,
                                    AVLinearPCMIsBigEndianKey   : @NO
                                    };
    
    //录音文件保存地址的URL
    //唯一的名字
    NSString *name = [[CZXMPPManager shareInstance].xmppStream generateUUID];
    self.recordName = [NSString stringWithFormat:@"%@_RECORD",name];
    
    //写入沙盒
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    //拼接全路径
//    NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_RECORD",name]];
    NSString *filePath = [path stringByAppendingPathComponent:self.recordName];
    
    NSURL *url = [NSURL URLWithString:filePath];
    
    NSError *error = nil;
    self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&error];
    
    if (error != nil) {
        NSLog(@"Init audioRecorder error: %@",error);
    }else{
        //准备就绪，等待录音，注意该方法会返回Boolean，最好做个成功判断，因为其失败的时候无任何错误信息抛出
        if ([self.audioRecorder prepareToRecord]) {
            NSLog(@"Prepare successful");
        }
    }
    // 开始录音
    [self.audioRecorder record];
}

- (void)saveRecord {
    NSLog(@"保存录音");
    
    [self.audioRecorder stop];
    
    
    /*
        发送录音
     */
//    NSError *urlerror = nil;
//    NSString *dataStr = [NSString stringWithContentsOfURL:self.audioRecorder.url encoding:NSUTF8StringEncoding error:&urlerror];
//    NSLog(@"url = %@",self.audioRecorder.url.absoluteString);
    
    NSData *recordData = [NSData dataWithContentsOfFile:self.audioRecorder.url.absoluteString];
    
//    NSError *dataError = nil;
//    NSData *recordData = [NSData dataWithContentsOfURL:self.audioRecorder.url options:NSDataReadingMappedIfSafe error:&dataError];
//    if (dataError) {
//        NSLog(@"dataError = %@",dataError);
//    }
    
//    NSData *recordData = [NSData dataWithContentsOfURL:self.audioRecorder.url];
    
    
    //发送文件  data:要发送的文件  name:指定文件名 toRecipient:接收者jid description:附加信息
    //接收者JID必须包含resource,否则出现错误
    NSError *error = nil;
    [[CZXMPPManager shareInstance].xmppOutgoingFileTransfer sendData:recordData named:self.recordName toRecipient:self.resourceJid description:nil error:&error];
    
    if (error) {
        NSLog(@"发送语音error = %@",error);
    }
    
    //打包消息 type:chat-单聊 ,groupchat-群聊
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.resourceJid];
    [message addBody:self.recordName];//%file%
    
    //添加subject,用于识别图片
    [message addSubject:@"RECORD"];
    
    // 打包入库
    [[XMPPMessageArchivingCoreDataStorage sharedInstance] archiveMessage:message outgoing:YES xmppStream:[CZXMPPManager shareInstance].xmppStream];
    
    //刷新界面
    [self fetchData];
    
}

- (void)promptCancelRecord {
    NSLog(@"提示取消录音");
    
}

- (void)CancelRecord {
    NSLog(@"取消录音");
    
    [self.audioRecorder stop];
}

- (void)continueRecord {
    NSLog(@"提示继续录音");
    
}






#pragma mark - UI事件

/**
 * 选择图片
 */
- (IBAction)sendPicClick:(id)sender {
    
    //图片选取
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //设置代理
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

// 录音
- (IBAction)record:(id)sender {
    if ([self.recordBtn.titleLabel.text isEqualToString:@"语音"]) {
        [self.recordBtn setTitle:@"打字" forState:UIControlStateNormal];
        self.messageTF.hidden = YES;
        self.pressTalk.hidden = NO;
        [self.view endEditing:YES];
    }else {
        [self.recordBtn setTitle:@"语音" forState:UIControlStateNormal];
        self.messageTF.hidden = NO;
        self.pressTalk.hidden = YES;
        [self.messageTF becomeFirstResponder];
    }
}

// 播放语音
- (IBAction)playerRecord:(UIButton *)sender {
    NSLog(@"播放录音");
    
    if (!self.audioPlayer.playing) {
        // 按钮所在cell的indexPath
        NSIndexPath *indexpath = [self.tableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
        
        //取出数据
        XMPPMessageArchiving_Message_CoreDataObject *aMessage = self.fetchedResultsController.fetchedObjects[indexpath.row];
        
        //获取图片路径
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        //拼接全路径
        NSString *filePath = [path stringByAppendingPathComponent:aMessage.body];
        NSURL *url = [NSURL URLWithString:filePath];
        
        NSError *error;
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        self.audioPlayer.delegate = self;
        if (error != nil) {
            NSLog(@"Wrong init player:%@", error);
        }else{
            [self.audioPlayer play];
        }
    }else {
        [self.audioPlayer pause];
    }

}



#pragma mark - tableView数据源和代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.fetchedResultsController.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //取出数据
    XMPPMessageArchiving_Message_CoreDataObject *aMessage = self.fetchedResultsController.fetchedObjects[indexPath.row];
    NSLog(@"composing = %@",aMessage.composing);
    
    //cell类型
    NSString *identifier = aMessage.isOutgoing? @"cell_outgoing" : @"cell_incomming";
    
    
    //判断是否是图片
    if ([aMessage.message.subject isEqualToString:@"IMAGE"]) {
        
        identifier = aMessage.isOutgoing? @"cell_outgoing_img" : @"cell_incomming_img";
        
    }else if ([aMessage.message.subject isEqualToString:@"RECORD"]) {
        identifier = aMessage.isOutgoing? @"cell_outgoing_record" : @"cell_incomming_record";
    }
    
    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    //赋值
    //头像
    UIImageView *avatarImgV = [cell viewWithTag:100];
    
    //使用个人资料头像模块获得头像
    NSData *avatarData = nil;
    
    //对方jid: self.resourceJid
    //自己jid:xmppStream.myJID
    
    if (aMessage.isOutgoing) {
        //我的头像
        avatarData = [[CZXMPPManager shareInstance].xmppvCardAvatarModule photoDataForJID:kCZ_myJID];
    }else{
        avatarData = [[CZXMPPManager shareInstance].xmppvCardAvatarModule photoDataForJID:self.resourceJid];
    }
    
    //是否有头像
    if (avatarData) {
        avatarImgV.image = [UIImage imageWithData:avatarData];
    }else{
        
        //默认头像
        avatarImgV.image = [UIImage imageNamed:@"DefaultHead"];
        
    }
    
    
    //账户名
    UILabel *bodyLb = [cell viewWithTag:101];
    
    //判断是否是图片
    if ([aMessage.message.subject isEqualToString:@"IMAGE"]) {
        
        bodyLb.text = @"这是图片";
        
        //获取图片路径
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        
        //拼接全路径
        NSString *filePath = [path stringByAppendingPathComponent:aMessage.body];
        
        
        //取出气泡视图
        CZChatImgView *imgView = [cell viewWithTag:102];
        
        [imgView setImage:[UIImage imageWithContentsOfFile:filePath] isOutgoing:aMessage.isOutgoing];
        
        
        
//        XMPPMessage *msg = aMessage.message;
//        
//        for (XMPPElement *node in msg.children) {
//            
//            // 取出消息的解码
//            NSString *base64str = node.stringValue;
//            NSData *data = [[NSData alloc]initWithBase64EncodedString:base64str options:0];
//            UIImage *image = [[UIImage alloc]initWithData:data];
//            //取出气泡视图
//            CZChatImgView *imgView = [cell viewWithTag:102];
//    
//            [imgView setImage:image isOutgoing:aMessage.isOutgoing];
//        }

        
    
    }else{
    
        bodyLb.text = aMessage.body;
    }
    
    
    
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //取出数据
    XMPPMessageArchiving_Message_CoreDataObject *aMessage = self.fetchedResultsController.fetchedObjects[indexPath.row];
    //是图片消息cell高度120
    if ([aMessage.message.subject isEqualToString:@"IMAGE"]) {
        
        return 120;
    }
    
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //取出数据
    XMPPMessageArchiving_Message_CoreDataObject *aMessage = self.fetchedResultsController.fetchedObjects[indexPath.row];
    //是图片消息cell高度120
    if ([aMessage.message.subject isEqualToString:@"IMAGE"]) {
        
        return 120;
    }
    
    return UITableViewAutomaticDimension;
}

#pragma mark - UITextFieldDelegate

/**
 * 按回车时调用
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    //发送消息 Type:类型-chat/groupchat
//    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.resourceJid];
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.jid];
    
    //添加消息body
    [message addBody:textField.text];
    
    //使用流发送消息元素
    [[CZXMPPManager shareInstance].xmppStream sendElement:message];
    
    
    //清空
    textField.text = @"";
    
    //刷新数据
    [self fetchData];
    
    return YES;
}

#pragma mark - 图片选取代理

/**
 * 图片选取完成
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSLog(@"%@",info);
    
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    
    //图片转成二进制
    NSData *imgData = UIImageJPEGRepresentation(img, 0.1);
    
    //唯一的名字B8CE920C-CE6C-426C-B144-33D0C2DB128D
//    B2E63D0E-1582-4BAA-825F-6DAB048EC636
    NSString *name = [[CZXMPPManager shareInstance].xmppStream generateUUID];
    
    //写入沙盒
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    //拼接全路径
    NSString *filePath = [path stringByAppendingPathComponent:name];
    
    NSLog(@"%@",filePath);
    
    //写入
    [imgData writeToFile:filePath atomically:YES];

    
    
    //发送文件  data:要发送的文件  name:指定文件名 toRecipient:接收者jid description:附加信息
    //接收者JID必须包含resource,否则出现错误
    NSError *error = nil;
    [[CZXMPPManager shareInstance].xmppOutgoingFileTransfer sendData:imgData named:name toRecipient:self.resourceJid description:nil error:&error];
    
    if (error) {
        NSLog(@"发送图片 error = %@",error);
    }
    
    //打包消息 type:chat-单聊 ,groupchat-群聊
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.resourceJid];
    [message addBody:name];//%file%
    
    //添加subject,用于识别图片
    [message addSubject:@"IMAGE"];
    
    [[XMPPMessageArchivingCoreDataStorage sharedInstance] archiveMessage:message outgoing:YES xmppStream:[CZXMPPManager shareInstance].xmppStream];
    
    //刷新界面
    [self fetchData];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

///**
// * 图片选取完成
// */
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
//
//    UIImage *image = info[UIImagePickerControllerOriginalImage];
//    
//    NSData *data = UIImagePNGRepresentation(image);
//    
//    [self sendMessageWithData:data bodyName:@"IMAGE"];
//    
//    [self dismissViewControllerAnimated:YES completion:nil];
//}
//
///** 发送二进制文件 */
//- (void)sendMessageWithData:(NSData *)data bodyName:(NSString *)name
//{
//    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.resourceJid];
//    
//    [message addBody:name];
//    
//    // 转换成base64的编码
//    NSString *base64str = [data base64EncodedStringWithOptions:0];
//    
//    // 设置节点内容
//    XMPPElement *attachment = [XMPPElement elementWithName:@"attachment" stringValue:base64str];
//    
//    // 包含子节点
//    [message addChild:attachment];
//    
//    // 发送消息
//    [[CZXMPPManager shareInstance].xmppStream sendElement:message];
//}




#pragma mark - XMPPStreamDelegate

/**
 * 收到消息的时候调用
 */
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{

    //从新获取数据刷新表格
    [self fetchData];
    
}

/**
 * 消息发送成功
 */
- (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message{

    
}

/**
 * 消息发送失败
 */
- (void)xmppStream:(XMPPStream *)sender didFailToSendMessage:(XMPPMessage *)message error:(NSError *)error{

}
/**
 * 消息将要发送
 */
- (XMPPMessage *)xmppStream:(XMPPStream *)sender willSendMessage:(XMPPMessage *)message {
    
    return message;
}



#pragma mark - XMPPIncomingFileTransferDelegate
// 接收文件成功
- (void)xmppIncomingFileTransfer:(XMPPIncomingFileTransfer *)sender didSucceedWithData:(NSData *)data named:(NSString *)name{
    NSLog(@"接收文件成功");
    //刷新
    [self fetchData];
}
// 接收文件失败
- (void)xmppIncomingFileTransfer:(XMPPIncomingFileTransfer *)sender didFailWithError:(NSError *)error {
    
}

- (void)xmppIncomingFileTransfer:(XMPPIncomingFileTransfer *)sender didReceiveSIOffer:(XMPPIQ *)offer {
    [sender acceptSIOffer:offer];
}


#pragma mark - XMPPOutgoingFileTransferDelegate
// 发送文件成功
- (void)xmppOutgoingFileTransferDidSucceed:(XMPPOutgoingFileTransfer *)sender{

}
// 发送文件失败
- (void)xmppOutgoingFileTransfer:(XMPPOutgoingFileTransfer *)sender didFailWithError:(NSError *)error{

    NSLog(@"发送文件失败 = %@",error);
}

#pragma mark - XMPPvCardAvatarDelegate
/**
 * 收到头像更新
 */
- (void)xmppvCardAvatarModule:(XMPPvCardAvatarModule *)vCardTempModule didReceivePhoto:(UIImage *)photo forJID:(XMPPJID *)jid{
    
    //刷新数据
    [self fetchData];
    
}

#pragma mark audio delegate
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"Finsh playing");
    
}

-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    NSLog(@"Decode Error occurred");
}

-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    NSLog(@"Finish record!");
}

-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
    NSLog(@"Encode Error occurred");
}

#pragma mark - lazy load





@end
